package com.serv.common.service.sys;

import java.util.Date;

import com.jfinal.aop.Aop;
import com.jfinal.kit.HashKit;
import com.serv.common.base.BaseService;
import com.serv.common.model.sys.Organization;
import com.serv.common.model.sys.User;

public class UserService extends BaseService<User> {
	private String admin = "admin";
	
	public UserService(){
		this.dao = User.dao;
	}
	
	public User getByUsername(String username){
		return dao.findFirst("select * from sys_user where username=?",username);
	}

	public void initAdmin() {
		User user = getByUsername(admin);
		if(user == null) {
			Organization root = Aop.get(OrganizationService.class).getRoot();
			
			String salt = HashKit.generateSalt(32);
			String encrypt = encrypt("123456",salt);
			user = new User()
				.set("id",uuid())
				.set("realname","超级管理员")
				.set("username",admin)
				.set("password",encrypt)
				.set("salt",salt)
				.set("status",1)
				.set("organization_id",root.get("id"))
				.set("created_at",new Date());
			
			if(user.save()) System.out.println("插入超级管理员数据,用户名为admin,密码为123456");
		}
	}
	
	public String encrypt(String password,String salt){
		return HashKit.md5(password + salt);
	}
}
